Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

StringBuilder and Buffer

StringBuilder Methods

StringBuilder and StringBuffer in Java have a variety of methods that allow for the manipulation and handling of strings. Here are some of the most commonly used methods in StringBuilder and StringBuffer append(): This method is used to append the string representation of a certain type of value to the sequence.
append() MethodStringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); // "Hello World"
insert(): This method inserts the string representation of a certain type of value into the sequence at the specified position.
insert() MethodStringBuilder sb = new StringBuilder("Hello World"); sb.insert(5, ","); // "Hello, World"
replace(): This method replaces the characters in a substring of this sequence with characters in the specified string.
replace() MethodStringBuilder sb = new StringBuilder("Hello, World"); sb.replace(7, 12, "Universe"); // "Hello, Universe"
delete() and deleteCharAt(): These methods are used to delete characters in a substring of this sequence. deleteCharAt() removes a single character at a specified location, while delete() removes a sequence of characters.
delete() and deleteCharAt() MethodStringBuilder sb = new StringBuilder("Hello, Universe"); sb.delete(7, 16); // "Hello," sb.deleteCharAt(5); // "Hello"
reverse(): This method causes this character sequence to be replaced by the reverse of the sequence.
reverse() MethodStringBuilder sb = new StringBuilder("Hello"); sb.reverse(); // "olleH"
toString(): This method returns a string representing the data in this sequence.
toString() MethodStringBuilder sb = new StringBuilder("Hello"); String str = sb.toString(); // "Hello"
These methods are available in both StringBuilder and StringBuffer classes. The main difference between StringBuilder and StringBuffer is that StringBuilder is not thread-safe whereas StringBuffer is thread-safe. So, if you are working in a single-threaded environment, using StringBuilder is more efficient. If you are working in a multi-threaded environment, you should use StringBuffer to ensure thread safety.

  📌TAGS

★String ★java ★string methods ★ StringBuilder ★ StringBuffer ★ methods

Tutorials